'use strict';

const { Model } = require('sequelize');
const crypto = require('crypto');

module.exports = (sequelize, DataTypes) => {
  class Contact extends Model {
    static associate(models) {
      // 定义关联
      Contact.hasMany(models.Message, { foreignKey: 'contactId', as: 'messages' });
      Contact.hasOne(models.CrmCustomer, { foreignKey: 'contactId', as: 'crmInfo' });
      Contact.belongsTo(models.WhatsappSession, { foreignKey: 'sessionId' });
    }
    
    // 加密电话号码
    static encryptPhone(phone, key) {
      if (!phone) return null;
      const iv = crypto.randomBytes(16);
      const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
      let encrypted = cipher.update(phone);
      encrypted = Buffer.concat([encrypted, cipher.final()]);
      return iv.toString('hex') + ':' + encrypted.toString('hex');
    }
    
    // 解密电话号码
    static decryptPhone(encryptedPhone, key) {
      if (!encryptedPhone) return null;
      const textParts = encryptedPhone.split(':');
      const iv = Buffer.from(textParts[0], 'hex');
      const encryptedText = Buffer.from(textParts[1], 'hex');
      const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
      let decrypted = decipher.update(encryptedText);
      decrypted = Buffer.concat([decrypted, decipher.final()]);
      return decrypted.toString();
    }
  }
  
  Contact.init({
    whatsappId: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    name: {
      type: DataTypes.STRING,
      allowNull: true
    },
    phone: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    profilePicUrl: {
      type: DataTypes.STRING,
      allowNull: true
    },
    lastActivity: {
      type: DataTypes.DATE,
      allowNull: true
    },
    lastMessageAt: {
      type: DataTypes.DATE,
      allowNull: true
    },
    lastMessageText: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    status: {
      type: DataTypes.STRING,
      allowNull: true,
      defaultValue: 'offline'
    },
    sessionId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'whatsapp_sessions',
        key: 'id'
      }
    },
    inCrm: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },
    crmId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'crm_customers',
        key: 'id'
      }
    },
    crmInfo: {
      type: DataTypes.STRING,
      allowNull: true
    }
  }, {
    sequelize,
    modelName: 'Contact',
    tableName: 'contacts',
    timestamps: true,
    hooks: {
      beforeCreate: (contact, options) => {
        // 加密电话号码
        if (contact.phone && process.env.ENCRYPTION_KEY) {
          contact.phone = Contact.encryptPhone(contact.phone, process.env.ENCRYPTION_KEY);
        }
      },
      beforeUpdate: (contact, options) => {
        // 如果电话号码改变，重新加密
        if (contact.changed('phone') && contact.phone && process.env.ENCRYPTION_KEY) {
          contact.phone = Contact.encryptPhone(contact.phone, process.env.ENCRYPTION_KEY);
        }
      }
    },
    indexes: [
      {
        name: 'contacts_whatsapp_id',
        fields: ['whatsappId']
      },
      {
        name: 'contacts_session_id',
        fields: ['sessionId']
      },
      {
        name: 'contacts_crm_id',
        fields: ['crmId']
      }
    ]
  });
  
  return Contact;
}; 